package org.xxpay.pay.channel.collpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.unify.AbstractPaymentConfig;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.Util;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;

/**
 * @Package org.xxpay.pay.channel.collpay
 * @Class: CollpayPaymentService.java
 * @Description:
 * @Author leo
 * @Date 2019/3/22 17:13
 * @Version
 **/
@Component
public class CollpayPaymentService extends BasePayment {
    private static final MyLog _log = MyLog.getLog(CollpayPaymentService.class);
    @Override
    public String getChannelName() {
        return CollpayConfig.CHANNEL_NAME;
    }


    @Override
    public JSONObject pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case CollpayConfig.CHANNEL_NAME_ALIPAY_COLL:
                retObj = doOrderReq(payOrder);
                break;
            case CollpayConfig.CHANNEL_NAME_UNIONQR:
                retObj = doOrderUnionQrReq(payOrder);
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }

        return retObj;
    }


    private JSONObject doOrderReq(PayOrder payOrder) {
        CollpayConfig collpayConfig = new CollpayConfig(getPayParam(payOrder));
        // 请求参数
        Map<String, Object> parameters = getRequestParameters(collpayConfig, payOrder);

        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(collpayConfig.getRequestUrl(), parameters, JSONObject.class);
        _log.info("{}返回数据:{}", getChannelName(), origin.toJSONString());

        JSONObject retObj = new JSONObject();

        if(origin.getInteger("code") == 0) {
            String channelOrderNo = origin.getString("orderNo");
            // 将订单更改为支付中
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), channelOrderNo);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},channelOrderNo={},result={}", getChannelName(), payOrder.getPayOrderId(), "", result);

            String codeUrl = origin.getString("payUrl");
            return buildPayResultOfCodeURL(retObj, payOrder, codeUrl);
        } else {
            retObj.put("errDes", "下单失败[" + origin.getString("msg") + "]");
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
            return retObj;
        }
    }

    private JSONObject doOrderUnionQrReq(PayOrder payOrder) {
        CollpayConfig collpayConfig = new CollpayConfig(getPayParam(payOrder));
        // 请求参数
        Map<String, Object> parameters = getRequestParameters(collpayConfig, payOrder);

        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(collpayConfig.getRequestUrl(), parameters, JSONObject.class);
        _log.info("{}返回数据:{}", getChannelName(), origin.toJSONString());

        JSONObject retObj = new JSONObject();

        if(origin.getInteger("code") == 0) {
            String channelOrderNo = origin.getString("orderNo");
            // 将订单更改为支付中
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), channelOrderNo);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},channelOrderNo={},result={}", getChannelName(), payOrder.getPayOrderId(), "", result);
            String codeUrl = origin.getString("payUrl");
            String formTxt = HtmlUtils.form(codeUrl, HtmlUtils.GET, Maps.newHashMap());

            return buildPayResultOfForm(retObj, payOrder, formTxt);
        } else {
            retObj.put("errDes", "下单失败[" + origin.getString("msg") + "]");
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
            return retObj;
        }
    }


    private Map<String, Object> getRequestParameters(CollpayConfig config, PayOrder order) {
        Map<String, Object> parameters = Maps.newHashMap();
        parameters.put("mchId", config.getMchId());
        parameters.put("amount", order.getAmount());
        parameters.put("outTradeNo", order.getPayOrderId());
        parameters.put("transType", config.getPayMode());
        if(StringUtils.isNotBlank(config.getChannelType())) {
            parameters.put("payType", config.getChannelType());
        }
        parameters.put("notifyUrl", payConfig.getNotifyUrl(getChannelName()));
        parameters.put("returnUrl", order.getReturnUrl());
        String signTxt = SignUtils.parameterText(parameters);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+config.getPrivateKey(), SignUtils.CHARSET_UTF8);
        parameters.put("sign", sign);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(parameters));
        return parameters;
    }

}
